<?php
// +------------------------------------------------------------------------------	
//	@desc Collected a number of function.Thank senior
//  @date Wed Aug 19 CST 2009
//  @author Fly Jin <flysharping@gamil.com>
// +------------------------------------------------------------------------------	

	function get_microtime() {
		list($usec, $sec) = explode(' ', microtime());
		return ((float)$usec + (float)$sec);
	}
	$TIME_START = get_microtime();
	
// +string函数	-------------------------------------------------------------
	function unescape($source){
		$result = '';
		$len = strlen($source);
		for ($i = 0; $i < $len; $i++){
			if ($source[$i] == '%' && $source[$i+1] == 'u'){
                $val = hexdec(substr($source, $i+2, 4));
                if ($val < 0x7f){
                	$result .= chr($val);
                }else if($val < 0x800) $result .= chr(0xc0|($val>>6)).chr(0x80|($val&0x3f));
                else $result .= chr(0xe0|($val>>12)).chr(0x80|(($val>>6)&0x3f)).chr(0x80|($val&0x3f));
                $i += 5;
            }else if ($source[$i] == '%'){
                $result .= urldecode(substr($source, $i, 3));
                $i += 2;
            }else{
            	 $result .= $source[$i];
            }
        }
        return $result;
	}
	
	function escape($str) {
		$str = iconv('utf-8', 'gb2312', $str);
		$sublen=strlen($str);
		$retrunString="";
		for ($i=0;$i<$sublen;$i++){
			if(ord($str[$i])>=127){
				$tmpString=bin2hex(iconv("gb2312","ucs-2",substr($str,$i,2)));
				//$tmpString=substr($tmpString,2,2).substr($tmpString,0,2);window下可能要打开此项
				$retrunString.="%u".$tmpString;
				$i++;
			} else {
				$retrunString.="%".dechex(ord($str[$i]));
			}
		}
		return $retrunString;
	} 
	
	// +------------------------------------------------------------
	//	@desc 统计UTF-8编码的字符长度
	//	一个中文，一个英文都为一个字
	//	@param string $str 字符串
	//	@return int 字符串长度
	// +------------------------------------------------------------
	function utf8_strlen($str) {
		return preg_match_all('/[\x00-\x7F\xC0-\xFD]/', $str, $dummy);
	}
	
	// +------------------------------------------------------------
	//	@desc 中文截取函数
	//	一个中文，一个英文都为一个字
	//	@param string $string 被截取的字符串
	//	@param int $len 被截取的长度
	//	@param boolean $slh 是否有省略号
	//	@param int $start 从第几个字开始截取
	//	@return string 截取后的字符串
	// +------------------------------------------------------------
	function utf8_substr($string, $len=14, $slh=0, $start=0){
		if ($slh AND utf8_strlen($string)>$len) {
			$str_slh = '…';
		}
		return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$start.'}'.
							'((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s', '$1', $string).$str_slh;
	}
	
	// +------------------------------------------------------------
	//	@desc 把字符串编码
	//	@param 编码用户输入的字符串string ，插入数据库中
	//	@param string|array $str 可以是数组或字符串
	//	@return string|array
	// +------------------------------------------------------------
	function html_encode($str){
		if (is_array($str)){
			foreach($str AS $k => $value) {
				$str[$k] = html_encode($value);
			}
		}else{
			$arr_sor = array('>', '<', "'", '"', chr(32), "\r\n");
			$arr_rep = array('&gt;', '&lt;', '&#39;', '&#34;', '&nbsp;', '<br/>');
			$str = str_replace($arr_sor, $arr_rep, trim($str));
		}
		return $str;
	}
	
	// +------------------------------------------------------------
	//	@desc 把字符串解码
	//	@param 解码数据库中 字符串，显示在textarea中
	//	@param string|array $str 可以是数组或字符串
	//	@return string|array
	// +------------------------------------------------------------
	function html_decode($str){
		if (is_array($str)){
			foreach($str AS $k => $value) {
				$str[$k] = html_decode($value);
			}
		}else{
			$arr_sor = array('&gt;', '&lt;', '&#39;', '&#34;', '&nbsp;', '<br/>');
			$arr_rep = array('>', '<', "'", '"', chr(32), "\r\n");
			$str = str_replace($arr_sor, $arr_rep, trim($str));
		}
		return $str;
	}
	
	// +------------------------------------------------------------
	//	@desc addslashes过滤，插入数据库，带有html字符串的数据
	//	@param string|array $str 可以是数组或字符串
	//	@return string|array
	// +------------------------------------------------------------

	function addslashes_str($str){
		if (!get_magic_quotes_gpc()) {
			if (is_array($str)) {
				foreach ($str as $key=>$value) {
					$str[$key] = addslashes_str($value);
				}
			} else {
				addslashes($str);
			}
		}else {
			return $str;
		}
		return $str;
	}
	
	// +------------------------------------------------------------
	//	@desc stripslashes还原数据，取出数据库，带有html字符串的数据
	//	@param string|array $str 可以是数组或字符串
	//	@return string|array
	// +------------------------------------------------------------
	function stripslashes_str($str){
		if (is_array($str)){
			foreach($str AS $id => $value) {
				$str[$id] = stripslashes_str($value);
			}
		}else{
			$str = stripslashes($str);
		}
		return $str;
	}
	
	// +------------------------------------------------------------
	//	@desc去掉 QUERY_STRING 中的某个参数的值，或清除一组变量
	//	@例如：$_SERVER["QUERY_STRING"] a=1&b=1&c=1
	//	@$var 为字符串，$var==a, 返回 b=1&c=1&a=
	//	@$var 为数组，$var==array(a,b), 返回 c=1
	//	@param string|array $var 被清除的字符串或数组
	// +------------------------------------------------------------
	function clear_url($var){
		$arr_url = array();
		parse_str($_SERVER["QUERY_STRING"], $arr_url);
		if (is_array($var)) {
			foreach ($var as $v) {
				unset($arr_url[$v]);
			}
		}else{
			unset($arr_url[$var]);
		}
		$str = '';
		if (!empty($arr_url)){
			$str = http_build_query($arr_url);
		}
		if (!is_array($var)) {
			$str = ($str ? $str.'&' : '').($var ? $var.'=' : '');
		}
		$str = str_replace('&', '&amp;', $str);
		return $str;
	}
	
	function clear_html($str){
		$search = array ("'<script[^>]*?>.*?</script>'si",  // 去掉 javascript
						 "'<[\/\!]*?[^<>]*?>'si",           // 去掉 HTML 标记
						 "'([\r\n])[\s]+'"                 // 去掉空白字符
						 );
		$replace = array ("",
						  "",
						  "\\1"
						  );
		$text = preg_replace ($search, $replace, $str);
		return $text;
	}
	
	// +------------------------------------------------------------
	//	@desc取得最后一个某字符$expstr以前的，$isstr=1 包括此字符
	//	@get_begin_str('smallphp.com.gif', '.', 1) = 'smallphp.com.'
	//	@param string $str;string $expstr 分隔符
	//	@param boolean $isstr 是否包含分隔符
	//	@return string 
	// +------------------------------------------------------------
	function get_begin_str($str, $expstr="/", $isstr=0){
		return substr($str, 0, strrpos($str, $expstr)+$isstr);
	}
	
	// +------------------------------------------------------------
	//	@desc取得最后一个某字符$expstr以后的，$isstr=1 包括此字符
	//	@例：get_end_str('smallphp.com.gif', '.', 1) = '.gif'
	//	@param string $str;string $expstr 分隔符
	//	@param boolean $isstr 是否包含分隔符
	//	@return string 
	// +------------------------------------------------------------
	function get_end_str($str, $expstr="/", $isstr=0){
		return substr($str, strrpos($str, $expstr)-strlen($str)+(empty($isstr)?1:0));
	}
	
	// +------------------------------------------------------------
	//	@desc在每个字符间插入文字(UTF8)
	//	@param string $str 被切分字符;int $len 切分字符个数
	//	@param string $what 要插入的文字;
	//	@param boolean $isin 在文字之间插入，还是之后
	//	@return string 
	// +------------------------------------------------------------
	function utf8_wordwrap($str, $len, $what, $isin=1){
		# usage: utf8_wordwrap("text",3,"<br>");
		# by tjomi4`, thanks to SiMM.
		# www.yeap.lv
		$from=0;
		$str_length = preg_match_all('/[\x00-\x7F\xC0-\xFD]/', $str, $var_empty);
		$while_what = $str_length / $len;
		$i = 0;
		while($i < round($while_what)){
			$string = preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
								   '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
								   '$1',$str);
			$arr[$i] = $string;
			$total .= $string.$what;
			$from = $from+$len;
			$i++;
		}
		$str = $isin ? implode($arr , $what) : $total;
		return $str;
	}
	
	
	// +------------------------------------------------------------
	//	@desc从字符串中截取指定数量的字符(UTF-8)
	//	@param string 源数据;integer 需截取的字符数;
	//	@param integer 开始位置，默认从第一个字符开始;string 字符串编码
	//	@param integer 字符串长度（不是以字节，而是以汉字为单位）
	//	@return string 截取的中文字符串
	// +------------------------------------------------------------
	function mbSubstr($str, $len, $start = 0, $encoding = 'UTF-8') {
		return mb_substr($str, $start, $len, $encoding);
	}

	function substring($string,$length=null){
        $len = strlen($string);
        $suffix = '';
        if($len >$length){
            $len =$length;
            $suffix = ' ... ';
            for ($idx = 0; $idx < $len; ){
                if (ord($string[$idx]) > 0x7f){
                    $idx += 3;
                }else{
                    $idx++;
                }
            }
            return substr($string, 0, $idx) . $suffix;
        }
        else return $string;    
    }

	// +------------------------------------------------------------
	//	@desc统计中文字符长度(UTF-8)
	//	@param string 中文字符串;string 字符串编码
	//	@return integer 字符串长度（不是以字节，而是以汉字为单位）
	// +------------------------------------------------------------
	function mbStrLen($str, $encoding = 'UTF-8') {
		return mb_strlen($str, $encoding);
	}

	// +------------------------------------------------------------
	//	@desc从字符串中截取指定数量的字符(UTF-8)
	//	@param string 源数据;integer 显示的最大字符;string 截取的中文字符串
	// +------------------------------------------------------------
	function maxMbsubstr($str, $len = 12, $postfix = '...') {
		return (mbStrLen($str) > $len ? mbSubstr($str, $len - 3) . $postfix : $str);
	}

// +array函数----------------------------------------------------------------

	// +------------------------------------------------------------
	//	@desc把数组的键、值联合起来，变成字符串
	//	@array('a'=>1, 'b'=>2)	a=1&b=2
	//	@param array $arr 文件路径;string $join_str 连接字符串@return array
	// +------------------------------------------------------------
	function arr_join($arr, $join_str="&"){
		$arr_str = array();
		foreach ((array)$arr as $k=>$v){
			$arr_str[] = $k."=".$v;
		}
		return join($join_str, $arr_str);
	}

	// +------------------------------------------------------------
	//	@desc把数组$arr 保存成 $var变量在 $file中
	//		 调用时，include(xxx); print_r($array);
	//	@param string $file 文件路径;array $arr 被保存的数组;@return boolean
	// +------------------------------------------------------------
	function arr_save_to_file($file, $arr){
		return file_put_contents($file, '<?php $array = '.preg_replace("/\s/i", "", var_export($arr, TRUE)).';?>');
	}
	
	// +------------------------------------------------------------
	//	@desc去掉数组中为空，且重复的值@array $arr
	// +------------------------------------------------------------
	function arr_remove_null($arr){
		if (is_array($arr)) {
			$arr = array_unique($arr);
			foreach((array)$arr AS $k=>$v){
				if(empty($v)){
					unset($arr[$k]);
				}
			}
		}else{
			$arr = array();
		}
		return $arr;
	}

	// +------------------------------------------------------------
	//	@desc将2维数组变成1维数组 array $arr_muli 二维数组	@return array1维数组
	// +------------------------------------------------------------
	function arr_muli_to_one($arr_muli){
		$arr = array();
		foreach ((array)$arr_muli AS $v){
			foreach($v AS $vv){
				$arr[] = $vv;
			}
		}
		return $arr;
	}

	// +------------------------------------------------------------
	//	@desc把数组转化为字符串 array $arr 数组	@return string
	// +------------------------------------------------------------
	function arr_to_str($arr) {
		global $arr_to_str;
		foreach ($arr AS $v) {
			if (is_array($v)) {
				arr_to_str($v);
			}else{
				$arr_to_str.= $v;
			}
		}
		return $arr_to_str;
	}
	
// +url函数------------------------------------------------------------------
	
	// +------------------------------------------------------------
	//	@desc获取当前地址栏 URL	@return string
	// +------------------------------------------------------------
	function get_url(){
		return "http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
	}
	
	// +------------------------------------------------------------
	//	@desc定时跳转 URL 要跳转去的页面，为空时，返回上一页@return void()
	// +------------------------------------------------------------
	function redirect_url($url="", $info="操作成功！", $time=3){
		$url = $url?$url:$_SERVER["HTTP_REFERER"];
		$str = get_url_html();
		$arr_sor = array('{info}', '{url}', '{time}');
		$arr_rep = array($info, $url, $time);
		echo str_replace($arr_sor, $arr_rep, $str);
		exit;
	}
	
	// +------------------------------------------------------------
	//	@desc页面跳转URL.$url跳转页面@return void()
	// +------------------------------------------------------------
	function redirect($url=''){
		$url = $url?$url:$_SERVER["HTTP_REFERER"];
		header("Location: ".$url);
		exit;
	}

	// +------------------------------------------------------------
	//	@desc 404页面跳转@return void()
	// +------------------------------------------------------------
	function redirect404(){
		header('HTTP/1.1 404 NotFound');
		echo '	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
				<html xmlns="http://www.w3.org/1999/xhtml">
				<head>
				<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
				<meta http-equiv="Cache-Control" content="no-cache">
				<meta http-equiv="refresh" content="5;URL=/">
				<style type="text/css">
				#errorPage #content{ width:auto; padding:40px;}
				.nav-right{ display:none;}
				.erro {background:#feffcf url(/Css/images/404bg.png) no-repeat 0 0; width:623px; height:208px; margin:35px auto; position:relative; }
				.erro ul li a { font-size:19px; line-height:300%; }
				#errorPage #content ul,.erro ul { position:absolute; top:70px; left:192px; list-style:none; color:#333}
				.erro h2{position:absolute; top:40px; left:191px; font-size:15px}
				.erro .icon{position:absolute; left:191px;top:692px}
				.nav-right {display:block;}
				#navigation .nav-right {margin-right:10px;_margin-right:4px;}
				</style>
				<title>- 抱歉，没有找到该网页.5秒后将自动返回首页</title>
				</head>
				<body id="errorPage">
				<div id="container">
					<div class="mainbox" style="background:none;">
						<div id="header">
							<div id="navigation" class="navigation-nologin"><ul class="nav-right"><br></ul></div>
						</div>
					<div>
					<div id="content">
						<div class="erro e404" >
						<h2>怎么出错啦？</h2>
						<ul>
							<li style="font-size:14px;">可能是网址输错啦，也可能是网页正在建设，下次再来吧...</li>
							<li style="font-size:16px;margin-top:24px;"><a href="/">返回首页</a>|<a href="javascript:history.go(-1)">返回上一页</a></li>
						</ul>
						</div>
					</div>	
				
					<div id="footer">
						<div class="copyright"></div>
					</div>
				</div>
				</body>
				</html>
				';
	}
	
	// +------------------------------------------------------------
	//	@descURL永久重定向.string $url 跳转到的URL.@return void()
	// +------------------------------------------------------------
	function redirect301($url){
		header('HTTP/1.1 301 Moved Permanently');
		redirect($url);
	}
	
	function redirect_back($msg=''){
		$str = '<script type="text/javascript">';
		$str.= $msg ? 'alert("'.str_replace('"', '\\"', $msg).'");' : '';
		$str.= 'history.back(-1);';
//		$str.= 'setTimeout(function(){history.back(-1);}, 1000);';
		$str.= '</script>';
		echo $str;
		exit;
	}
	
	function get_url_html() {
		$str ='	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
				<html xmlns="http://www.w3.org/1999/xhtml">
				<head>
				<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
				<title>{time}秒后跳转</title>
				<style type="text/css">
					div{
						position: absolute;
						top: 50%;margin-left:-200px;
						left: 50%;margin-top:-60px;
						text-align:center;
						border:1px solid #3399FF;background:#F7FBFF;
						width:400px;height:70px;
						font-size:12px;
					}
					div p{margin:0;float:left;width:100%;line-height:25px;height:25px;}
					div p.info{margin-top:10px;}
					a{color:#000;}
				</style>
				</head>
				<meta http-equiv="refresh" CONTENT="{time};URL={url}">
				<body>
				<div>
					<br><p class="info">{info}</p>
				</div>
				</body>
				</html>';
		return $str;
	}
	
// +Anther Function-------------------------------------------------------------
	
	// +------------------------------------------------------------
	//	@desc获取客户端IP	@return string
	// +------------------------------------------------------------
	function get_ip(){
		if (getenv('HTTP_CLIENT_IP')){
			$ip = getenv('HTTP_CLIENT_IP');
		}elseif (getenv('HTTP_X_FORWARDED_FOR')){
			$ip = getenv('HTTP_X_FORWARDED_FOR');
		}elseif (getenv('HTTP_X_FORWARDED')){
			$ip = getenv('HTTP_X_FORWARDED');
		}elseif (getenv('HTTP_FORWARDED_FOR')){
			$ip = getenv('HTTP_FORWARDED_FOR');
		}elseif (getenv('HTTP_FORWARDED')){
			$ip = getenv('HTTP_FORWARDED');
		}else{
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		return $ip;
	}
	
	// +------------------------------------------------------------
	//	@desc Format print	@return array
	// +------------------------------------------------------------
	function pr($arr){
		echo '<pre style="text-align:left">';
		print_r($arr);
		echo '</pre>';
	}
	function vr($arr){
		echo '<pre style="text-align:left">';
		var_dump($arr);
		echo '</pre>';
	}
	
	// +------------------------------------------------------------
	//	@desc 从一个数组中获取指定名称的变量值
	//	@example getParam($_GET, 'userId', 0)
	// +------------------------------------------------------------
	function getParam(& $arr, $name, $def = Null) {
		return (isset($arr[$name])) ? $arr[$name] : $def;
	}
		
	function escape_data($date){
		if (ini_get('magic_quotes_gpc')) {
			$date=stripslashes($date);
		}
		if (function_exists('mysql_real_escape_string')) {
			$date=mysql_real_escape_string(trim($date));
		}else{
			$date=mysql_escape_string(trim($date));
		}
	}

	function clear_tag($str){
		return join(',', explode(',', preg_replace("/[ ,]+/", ',', $str)));
	}
	
	function write_excel($objPHPExcel, $filename){
		require_once('PHPExcel'.DS.'Writer'.DS.'Excel5.php');
		$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
		header("Pragma: public");
		header("Expires: 0");
		header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
		header("Content-Type:application/force-download");
		header("Content-Type:application/vnd.ms-execl");
		header("Content-Type:application/octet-stream");
		header("Content-Type:application/download");;
		header('Content-Disposition:attachment;filename="'.$filename.'"');
		header("Content-Transfer-Encoding:binary");
		$objWriter->save('php://output');
	}
?>